package com.ecomcs.annuaire;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;

import com.google.appengine.api.oauth.OAuthService;
import com.google.appengine.api.oauth.OAuthServiceFactory;
import com.google.appengine.api.users.User;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.data.extensions.PhoneNumber;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.Namespaces;
import com.google.gdata.util.PreconditionFailedException;
import com.google.gdata.util.ServiceException;


public class GoogleConnector {
	ContactsService myService;
	
	String connectorUser = "admin.apps@mf-world.com";
	String connectorPasswordUser = "password007";
	String domainName = "mf-world.com";
	
	
	public GoogleConnector() throws AuthenticationException{
		System.out.println("ok");
		System.out.println("la");
/*
        User user = null;
        try {
            OAuthService oauth = OAuthServiceFactory.getOAuthService();
            user = oauth.getCurrentUser();

        } catch (Exception e) {
            // The consumer made an invalid OAuth request, used an access token that was
            // revoked, or did not provide OAuth information.
            // ...
        }
        
        this.myService = new ContactsService("annuaire-exampleApp-1");
		this.myService.set
		*/		
		
		
		this.myService = new ContactsService("annuaire-exampleApp-1");
		String next = "http://localhost:8888/annuaire";
		String scope = "http://www.google.com/m8/feeds/";
		boolean secure = false;
		boolean session = true;
		String authSubLogin = AuthSubUtil.getRequestUrl(next, scope, secure, session);
		System.out.println(authSubLogin);
		String token = AuthSubUtil.getTokenFromReply(authSubLogin);
		System.out.println(token);
		String sessionToken = null;
		try {
			sessionToken = AuthSubUtil.exchangeForSessionToken(token, null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (GeneralSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.myService.setAuthSubToken(sessionToken, null);
		

		
		/*
		this.myService = new ContactsService("annuaire-exampleApp-1");
		this.myService.setUserCredentials(this.connectorUser, this.connectorPasswordUser);
		*/
	
/*		} catch (AuthenticationException e) {
			e.printStackTrace();
		}*/
	}
	
	void createSharedContact(String name, String note, String contactEmail){
		
		ContactEntry contact = new ContactEntry();
		contact.setTitle(new PlainTextConstruct(name));
		contact.setContent(new PlainTextConstruct(note));
		
		Email email = new Email();
		email.setAddress(contactEmail);
		email.setRel("http://schemas.google.com/g/2005#home");
		email.setPrimary(true);
		contact.addEmailAddress(email);
		
		ExtendedProperty favouritecar = new ExtendedProperty();
		favouritecar.setName("favourite car");
		favouritecar.setValue("Toyota Supra mk4 TwinTurbo");
		contact.addExtendedProperty(favouritecar);
		
		URL postUrl = null;
		try {
			postUrl = new URL("https://www.google.com/m8/feeds/contacts/"+this.domainName+"/full");
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		ContactEntry back = null;
		try {
			back = this.myService.insert(postUrl, contact);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println();
		System.out.println(back.getContent());
	}
	
	public void showSharedContact(){
		URL feedUrl = null;
		try {
			feedUrl = new URL("https://www.google.com/m8/feeds/contacts/"+this.domainName+"/full");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		ContactFeed resultFeed = null;
		try {
			resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println(resultFeed.getTitle().getPlainText());
		
		System.out.println("Numbers of contact(s) : "+ resultFeed.getEntries().size());
		
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			
			ContactEntry entry = resultFeed.getEntries().get(i);
			System.out.println(entry.getTitle().getPlainText());
			for(int j = 0; j<entry.getEmailAddresses().size(); j++){
				System.out.println(entry.getEmailAddresses().get(j).getAddress());
			}
			for(int j = 0; j<entry.getPhoneNumbers().size(); j++){
				System.out.println(entry.getPhoneNumbers().get(j).getPhoneNumber());
			}
		}
		
	}
	
	/*
	public void showDomainContact(){
		
		URL feedUrl = null;
		try {
			feedUrl = new URL("https://www.google.com/m8/feeds/profiles/domain/"+this.domainName+"/full");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		ContactFeed resultFeed = null;
		try {
			resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println(resultFeed.getTitle().getPlainText());
		System.out.println("Numbers of contact(s) : "+ resultFeed.getEntries().size());
		
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			ContactEntry entry = resultFeed.getEntries().get(i);
			System.out.println(entry.getTitle().getPlainText());
			for(int j = 0; j<entry.getEmailAddresses().size(); j++){
				System.out.println(entry.getEmailAddresses().get(j).getAddress());
			}
			for(int j = 0; j<entry.getPhoneNumbers().size(); j++){
				System.out.println(entry.getPhoneNumbers().get(j).getPhoneNumber());
			}

		    
		}
	
	
	}*/
	
	
	public void showDomainContact(PrintWriter out){
		
		URL feedUrl = null;
		try {
			feedUrl = new URL("https://www.google.com/m8/feeds/profiles/domain/"+this.domainName+"/full");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		ContactFeed resultFeed = null;
		try {
			resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		out.println(resultFeed.getTitle().getPlainText());
		out.println("Numbers of contact(s) : "+ resultFeed.getEntries().size());
		
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			ContactEntry entry = resultFeed.getEntries().get(i);
			out.println(entry.getTitle().getPlainText());
			/*for(int j = 0; j<entry.getEmailAddresses().size(); j++){
				out.println(entry.getEmailAddresses().get(j).getAddress());
			}
			for(int j = 0; j<entry.getPhoneNumbers().size(); j++){
				out.println(entry.getPhoneNumbers().get(j).getPhoneNumber());
			}*/

		    
		}
	
	
	}	  
	
	/*
	public void findProfile(String userAdress){
		URL feedUrl = null;
		try {
			feedUrl = new URL("https://www.google.com/m8/feeds/profiles/domain/"+this.domainName+"/full");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		ContactFeed resultFeed = null;
		try {
			resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class);
		} catch (IOException | ServiceException e) {
			e.printStackTrace();
		}
		
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			ContactEntry entry = resultFeed.getEntries().get(i);
			for(int j = 0; j<entry.getEmailAddresses().size(); j++){
				if (entry.getEmailAddresses().get(j).getAddress().equals(userAdress)){
					System.out.println(entry.getTitle().getPlainText());
					System.out.println(entry.getLinks().get(0).getHref());
				}
			}
		}
	
	}
	*/
	
	public ContactEntry getDomainContact(String userAdress){
		URL feedUrl = null;
		try {
			feedUrl = new URL("https://www.google.com/m8/feeds/profiles/domain/"+this.domainName+"/full");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		ContactFeed resultFeed = null;
		try {
			resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			ContactEntry entry = resultFeed.getEntries().get(i);
			for(int j = 0; j<entry.getEmailAddresses().size(); j++){
				if (entry.getEmailAddresses().get(j).getAddress().equals(userAdress)){
					return entry;
				}
			}
		}
		return null;
	
	}

	
	public ContactEntry getSharedContact(String userAdress){
		URL feedUrl = null;
		try {
			feedUrl = new URL("https://www.google.com/m8/feeds/contacts/"+this.domainName+"/full");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		ContactFeed resultFeed = null;
		try {
			resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		/*
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			ContactEntry entry = resultFeed.getEntries().get(i);
			System.out.println(entry.getTitle().getPlainText());
		    System.out.println(entry.getEmailAddresses().get(0).getAddress());
		}*/
		
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			ContactEntry entry = resultFeed.getEntries().get(i);
			for(int j = 0; j<entry.getEmailAddresses().size(); j++){
				if (entry.getEmailAddresses().get(j).getAddress().equals(userAdress)){
					return entry;
				}
			}
		}
		return null;
		
	}
	
	
	public void updateDomainContactPhoneNumber(ContactEntry entryToUpdate, String number)
		    throws ServiceException, IOException {
		PhoneNumber phoneNumber = new PhoneNumber();
		phoneNumber.setPhoneNumber(number);
		phoneNumber.setRel(Namespaces.inflate("work"));
		
		entryToUpdate.addPhoneNumber(phoneNumber);
		entryToUpdate.getStatus().setIndexed(false);
		
		URL editUrl = new URL(entryToUpdate.getEditLink().getHref());
		ContactEntry contactEntry = null;
		try {
			contactEntry = myService.update(editUrl, entryToUpdate);

		} 
		catch (PreconditionFailedException e) {
			e.printStackTrace();
		}
	}
	
	
	public void updateSharedContactPhoneNumber(ContactEntry entryToUpdate, String number)
		    throws ServiceException, IOException {
		PhoneNumber phoneNumber = new PhoneNumber();
		phoneNumber.setPhoneNumber(number);
		phoneNumber.setRel(Namespaces.inflate("work"));
		
		entryToUpdate.addPhoneNumber(phoneNumber);
		//entryToUpdate.getStatus().setIndexed(false);
		
		URL editUrl = new URL(entryToUpdate.getEditLink().getHref());
		ContactEntry contactEntry = null;
		try {
			contactEntry = myService.update(editUrl, entryToUpdate);

		} 
		catch (PreconditionFailedException e) {
			e.printStackTrace();
		}
	}
	
	

	
}
